$NG.AllReady(function (
    editPage,
    { useAction, useValuesChange, useUpdateRows, useDataIndexChange, useClick }
) {
	const mstform = $NG.getCmpApi("p_form_svc_cost_budget_chg")
	const dgrid1 = $NG.getCmpApi("p_form_svc_labor_budget_chg")
	const dgrid2 = $NG.getCmpApi("p_form_svc_daliy_budget_chg")
    getCntCount("p_form_svc_cost_budget_chg","u_cnt",CntEvent)
    getPtInfoByPhid()
    useValuesChange(({args})=>{
        console.log(`项目监听`, args);
		getPtInfoByPhid()
		cntMFilter()
        $NG.updateState((updater)=>{
            updater.data.p_form_svc_cost_budget_chg.setProps({
                u_pc_no: args[0].phid_pc.PhId,
				u_cnt:{
					label:null,
					value:null
				},
            })
            setTimeout(()=>{
                cntMFilter()
            },200)
        })
        getCntCount("p_form_svc_cost_budget_chg","u_cnt",CntEvent)
    }, "p_form_svc_cost_budget_chg.phid_pc")

// 添加列
useValuesChange(({ args }) => {
	console.log(args[0]);
	CntEvent()
}, "p_form_svc_cost_budget_chg.u_cnt");
function CntEvent(){
    getCntInfo()
	dgrid1.clearRows();
	dgrid2.clearRows();
	setTimeout(() => {
		// 赋值
		function _sum(num) {
			$NG.updateState((updater) => {
				updater.data.p_form_svc_cost_budget_chg.setProps({
					u_total_svc_amt_ori: num
				})
			})
		}
		// 临时存储上一次的费用
		const _countMaps = {
			_d1: 0,
			_d2: 0,
			_d3: 0,
			set d1(value) {
				this._d1 = value
				_sum(this._d1 + this._d2 + this._d3)
			},
			set d2(value) {
				this._d2 = value
				_sum(this._d1 + this._d2 + this._d3)
			},
			set d3(value) {
				this._d3 = value
				_sum(this._d1 + this._d2 + this._d3)
			},
		}
		Object.defineProperties(_countMaps, {
			_d1: {
				configurable: false,
				writable: true,
				enumerable: false,
				value: 0
			},
			_d2: {
				configurable: false,
				writable: true,
				enumerable: false,
				value: 0
			},
			_d3: {
				configurable: false,
				writable: true,
				enumerable: false,
				value: 0
			},
		})
		if (dgrid1) {
			$NG.execServer('getSvcLaborBudgetInfo', {
				cnt: mstform.getItem('u_cnt').getValue()
			}, function (res) {

				let _data = null
				if (typeof res.data === 'string') {
					_data = JSON.parse(res.data)
				} else {
					_data = res.data
				}
				console.log(`测试测试`, _data,res);
				//默认增行,批量新增表体数据
				var gridArr = []; //定义表体数组
				var gridCount = res.count; //增加的行数,可根据从数据库从取出的数据总数增行
				for (var i = 0; i < gridCount; i++) {
					var gridObj = {
					};
					//对表体字段进行赋值,可以取数据库中的值进行赋值

					// 年度
					gridObj.u_year = _data[i].extendObjects.u_year;
					// 人员岗位
					gridObj.u_position = { label: _data[i].extendObjects.position_name, value: _data[i].extendObjects.position_phid }
					// 人员费率
					gridObj.u_personnel_rate = _data[i].extendObjects.u_personnel_rate;
					// 人工费合计
					gridObj.u_svc_labor_amt_ori = _data[i].extendObjects.u_amt;
					gridObj.u_svc_labor_amt = _data[i].extendObjects.u_amt;
					// 数量
					gridObj.u_qty = _data[i].extendObjects.u_qty;
					gridObj.u_qty_ori = _data[i].extendObjects.u_qty;
					gridObj.u_source_phid = _data[i].extendObjects.phid

					// 1- 12 月
					for (let j = 1; j <= 12; j++) {
						const _str = `u_man_days_${j < 10 ? '0' + j : j}`
						const _str_ori = `u_man_days_${j < 10 ? '0' + j : j}_ori`
						gridObj[_str] = _data[i].extendObjects[_str];
						gridObj[_str_ori] = _data[i].extendObjects[_str];
					}
					gridArr.push(gridObj);
				}
				//调用新增表体行数据的函数
				let _count = 0;
				gridArr.forEach(item => {
					_count += item.u_svc_labor_amt_ori
				})
				$NG.updateState((updater) => {
					_countMaps.d1 = _count
					updater.data.p_form_svc_cost_budget_chg.setProps({
						u_total_svc_labor_amt_ori: _count,
					})
				})
				dgrid1.addRows(gridArr);
			})
		}
		if (dgrid2) {
			$NG.execServer('getSvcDaliyBudgetInfo', {
				cnt: mstform.getItem('u_cnt').getValue()
			}, function (res) {
				let _data = null
				if (typeof res.data === 'string') {
					_data = JSON.parse(res.data)
				} else {
					_data = res.data
				}
				console.log(`测试测试日常`, _data);
				//默认增行,批量新增表体数据
				var gridArr = []; //定义表体数组
				var gridCount = res.count; //增加的行数,可根据从数据库从取出的数据总数增行
				for (var i = 0; i < gridCount; i++) {
					//对表体字段进行赋值,可以取数据库中的值进行赋值
					var gridObj = {
					};
					gridObj.u_year = _data[i].extendObjects.u_year;
					gridObj.u_annual_svc_amt = _data[i].extendObjects.u_annual_svc_amt;
					gridObj.u_annual_svc_amt_ori = _data[i].extendObjects.u_annual_svc_amt;
					gridObj.u_expense_code = _data[i].extendObjects.u_expense_code;
					gridObj.u_expense_name = _data[i].extendObjects.u_expense_name;
					gridObj.u_expense_description = _data[i].extendObjects.u_expense_description
					gridObj.u_source_phid = _data[i].extendObjects.phid
					// 1- 12 月
					for (let j = 1; j <= 12; j++) {
						const _str = `u_expenses_${j < 10 ? '0' + j : j}`
						const _str_ori = `u_expenses_${j < 10 ? '0' + j : j}_ori`
						gridObj[_str] = _data[i].extendObjects[_str];
						gridObj[_str_ori] = _data[i].extendObjects[_str];
					}
					gridArr.push(gridObj);
				}
				let _count = 0;
				gridArr.forEach(item => {
					_count += item.u_annual_svc_amt
				})
				$NG.updateState((updater) => {
					_countMaps.d2 = _count
					updater.data.p_form_svc_cost_budget_chg.setProps({
						u_total_daily_amt_ori: _count
					})
				})
				//调用新增表体行数据的函数
				dgrid2.addRows(gridArr);
				dgrid2.refreshView()
			})
		}
	}, 200)
}
	useUpdateRows(({args})=>{
		caculatedgrid()
	}, "p_form_svc_labor_budget_chg")
	useUpdateRows(({args})=>{
		caculatedgrid()
	}, "p_form_svc_daliy_budget_chg")
	function caculatedgrid() {
        let u_total_impl_labor_amt = 0; //实施人工费
        let u_total_daily_amt = 0; //合计日常费用
        let u_total_sec_dev_amt = 0; //合计二次开发费用
        let u_total_impl_amt = 0; //合计总费用

        const Rows1 = dgrid1.getRows(); //设备清单页签
        const Rows2 = dgrid2.getRows(); //实施费页签
        Rows1.forEach((items) => {
            u_total_impl_labor_amt += parseFloat(items.u_svc_labor_amt) || 0; //合同现额
        });
        Rows2.forEach((items) => {
            u_total_daily_amt += parseFloat(items.u_annual_svc_amt);
        });

        u_total_impl_amt =
            u_total_impl_labor_amt + u_total_daily_amt + u_total_sec_dev_amt;

        $NG.updateState((updater) => {
            updater.data.p_form_svc_cost_budget_chg.setProps({
                u_total_svc_labor_amt: u_total_impl_labor_amt, //
                u_total_daily_amt: u_total_daily_amt, //
                u_total_svc_amt: u_total_impl_amt, //
            });
        });
    }
    function cntMFilter() {
		if (!mstform.getItem("phid_pc").getValue()) {
			return;
		}
		$NG.updateUI((updater, state) => {
			updater.fieldSetForm.p_form_svc_cost_budget_chg.u_cnt.setProps({
				onBeforeOpen: async () => {
					var phid_pc = $NG
						.getCmpApi("p_form_svc_cost_budget_chg")
						.getItem("phid_pc")
						.getValue();
					if (!phid_pc) {
						$NG.alert("请先选择项目");
						return false;
					} else {
						return true;
					}
				},
				...(!!$NG
					.getCmpApi("p_form_svc_cost_budget_chg")
					.getItem("phid_pc")
					.getValue() && {
					clientSqlFilter: {
						bill_type: 1,
						phid_pc: $NG
							.getCmpApi("p_form_svc_cost_budget_chg")
							.getItem("phid_pc")
							.getValue(),
					},
				}),
			});
		});
	}
	function getPtInfoByPhid() {
		if (mstform.getItem("phid_pc").getValue()) {
			$NG.execServer(
				"getPtInfoByPhid",
				{ phid: mstform.getItem("phid_pc").getValue() },
				function (res) {
					const datas = JSON.parse(res.data)[0].extendObjects;
					console.log(datas);
					//帮助字段赋值
					$NG.updateState((updater) => {
						updater.data.p_form_svc_cost_budget_chg.setProps({
							// u_agreed_sts_dt: datas.start_date, //计划完工日期
							// u_agreed_pcl_dt: datas.end_date, //计划竣工日期
							u_pc_no: datas.pc_no, //项目编码
							//项目类型
							u_pc_type:{
								label:datas.type_name,
								value:datas.type_phid
							},
							u_sqgw: {
								//售前顾问
								value: datas.user_sqgw_phid,
								label: datas.user_sqgw_name,
							},
							u_division: {
								//事业部or组织
								value: datas.phid_org_phid,
								label: datas.phid_org_name,
							},
							u_regional_center: {
								//区域中心
								value: datas.regional_center_phid,
								label: datas.regional_center_name,
							},
							u_product_line: {
								//产品线
								value: datas.midwife_phid,
								label: datas.midwife_name,
							},
						});
					});
				}
			);
		}
	}
	function getCntInfo(){
        $NG.execServer(
            "getCntMInfoByPhid",
            { phid: mstform.getItem("u_cnt").getValue() },
            function (res) {
                const datas = JSON.parse(res.data)[0].extendObjects;
                console.log(`合同：`,datas);
                //帮助字段赋值
                $NG.updateState((updater) => {
                    updater.data.p_form_svc_cost_budget_chg.setProps({
                        u_agreed_sts_dt: datas.start_dt, //计划完工日期
                        u_agreed_pcl_dt: datas.end_dt, //计划竣工日期
                        u_cnt_no:datas.pcm_no
                    });
                });
            }
        );
    }
});

//获取合同数量
function getCntCount(table,key,fun){
    if(!$NG.getCmpApi(table).getItem("phid_pc").getValue()) return
    $NG.execServer("getCntCount",{type:1,phid_pc:$NG.getCmpApi(table).getItem("phid_pc").getValue()},(res)=>{
      console.log(res,'count');
      switch(res.count){
        case 0:
          return
        case 1:
          const datas = JSON.parse(res.data)[0].extendObjects
          const temp_map = {}
          temp_map[key] = datas.phid
          temp_map[`${key}_EXName`] = datas.bill_name
          $NG.updateState((updater)=>{
            updater.data[table].setProps({
              ...temp_map
            })
            setTimeout(()=>{
              if(fun){
                fun()
              }
            },200)
          })
      }
    })
  }
      